package com.ct.utils;

import cn.hutool.core.io.FileTypeUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * Excel 文件 导出工具
 * </p>
 */
public class MyEasyExcel {

    public final static String EXL_FILE_XLSX = ".xlsx";
    public final static String EXL_FILE_XLS = ".xls";
    public final static String EXL_FILE_CSV = ExcelTypeEnum.CSV.getValue();

    /**
     * xlsx 做文件类型判断时为zip，神奇
     */
    private static final String FILE_ZIP = "zip";

    /**
     * xlsx 做文件类型判断时为jar，神奇
     */
    private static final String FILE_JAR = "jar";



    /**
     * @param outClass   每行对应的类
     * @param fileNameIn 名称
     */
    public static void outPut(HttpServletResponse response, Class outClass, String fileNameIn, List list) throws IOException {
        //.openxmlformats-officedocument.spreadsheetml.sheet
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(fileNameIn, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + EXL_FILE_XLSX);
        EasyExcel.write(response.getOutputStream(), outClass).sheet("sheet1").doWrite(list);
    }

    /**
     * @param outClass   每行对应的类
     * @param fileNameIn 名称
     */
    public static void outPut(HttpServletResponse response, Class outClass, String fileNameIn, List list,Set<String> includeColumnFiledNames) throws IOException {
        //.openxmlformats-officedocument.spreadsheetml.sheet
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(fileNameIn, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + EXL_FILE_XLSX);
        EasyExcel.write(response.getOutputStream(), outClass)
                .includeColumnFieldNames(includeColumnFiledNames)
                .sheet("sheet1").doWrite(list);
    }


    /**
     * @param outClass   每行对应的类
     * @param fileNameIn 名称
     */
    public static void outPutXls(HttpServletResponse response, Class outClass, String fileNameIn, List list) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(fileNameIn, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + EXL_FILE_XLS);
        EasyExcel.write(response.getOutputStream(), outClass).excelType(ExcelTypeEnum.XLS)
                .sheet("sheet1").doWrite(list);
    }


    /**
     * @param outClass   每行对应的类
     * @param fileNameIn 名称
     */
    public static void outPutCsv(HttpServletResponse response, Class outClass, String fileNameIn, List list) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(fileNameIn, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ExcelTypeEnum.CSV.getValue());

        //加上UTF-8文件的标识字符,如果不写入这几个字节，会导致用Excel打开时，中文显示乱码
        //response.getOutputStream().write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
        EasyExcel.write(response.getOutputStream(), outClass)
                .excelType(ExcelTypeEnum.CSV)
                .charset(Charset.forName("GBK"))
                .sheet("sheet1")
                .doWrite(list);
    }


    /**
     * @param outClass   每行对应的类
     * @param fileNameIn 名称
     * @param includeColumnFiledNames  根据用户传入字段进行导出
     */
    public static void outPutCsv(HttpServletResponse response, Class outClass,
                                 String fileNameIn, List list, Set<String> includeColumnFiledNames) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(fileNameIn, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ExcelTypeEnum.CSV.getValue());


        //加上UTF-8文件的标识字符,如果不写入这几个字节，会导致用Excel打开时，中文显示乱码
        response.getOutputStream().write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
        EasyExcel.write(response.getOutputStream(), outClass)
                .includeColumnFieldNames(includeColumnFiledNames)
                .excelType(ExcelTypeEnum.CSV)
                .sheet("sheet1")
                .doWrite(list);
    }



    /**
     * 检测文件类型
     *
     * @param file            导入的问题
     * @param isCheckRealType 检测真实文件类型，但不同的软件编辑后类型不一，比较麻烦
     */
    public static boolean checkFileType(MultipartFile file, boolean isCheckRealType) {
        String filename = file.getOriginalFilename();
        String fileType = filename.substring(filename.lastIndexOf("."));
        //先判断后缀名
        if (EXL_FILE_XLS.equalsIgnoreCase(fileType) || EXL_FILE_XLSX.equalsIgnoreCase(fileType) || EXL_FILE_CSV.equalsIgnoreCase(fileType)) {
            if (!isCheckRealType) {
                return true;
            } else {
                String type;
                try {
                    type = FileTypeUtil.getType(file.getInputStream(), filename);
                    //根据首部字节判断文件类型
                    if (FILE_JAR.contains(type) || FILE_ZIP.contains(type) || EXL_FILE_CSV.contains(type) || EXL_FILE_XLS.contains(type) || EXL_FILE_XLSX.contains(type)) {
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 检测文件类型
     *
     * @param file 导入的问题
     */
    public static String getFileType(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String fileType = filename.substring(filename.lastIndexOf("."));
        return fileType;
    }

    public static void read(InputStream inputStream, Class head, AnalysisEventListener ajglListener, String fileType) throws Exception {
        if (EXL_FILE_XLS.equalsIgnoreCase(fileType)) {
            EasyExcel.read(inputStream, head, ajglListener).excelType(ExcelTypeEnum.XLS).sheet().doRead();
        } else if (EXL_FILE_CSV.equalsIgnoreCase(fileType)) {
            //importCsv(inputStream,  ajglListener);dsfas
            EasyExcel.read(inputStream, head, ajglListener).excelType(ExcelTypeEnum.CSV).sheet().doRead();
        } else {
            EasyExcel.read(inputStream, head, ajglListener).sheet().doRead();
        }
    }

    public static void importCsv(InputStream inputStream, AnalysisEventListener readListener) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
        int count = 0;
        Map<Integer, String> headMap = new HashMap<>();
        while (true) {
            count++;
            String s = reader.readLine();
            if (s != null) {
                // 数据头
                if (count == 1) {
                    String[] split = s.split(",");
                    for (int i = 0; i < split.length; i++) {
                        headMap.put(i, specialUnicode(split[i]));
                    }
                    readListener.invokeHeadMap(headMap, null);
                } else {
                    String[] split = s.split(",");
                    Map<Integer, String> entity = new HashMap<>();
                    for (int i = 0; i < split.length; i++) {
                        entity.put(i, split[i]);
                    }
                    readListener.invoke(entity, null);
                }
            } else {
                break;
            }
        }
        readListener.doAfterAllAnalysed(null);
    }


    /**
     * 去除 字符串收尾的 特殊的Unicode [ "\uFEFF" ]
     * csv 文件可能会带有该编码
     */
    public static String specialUnicode(String str) {
        if (str.startsWith("\uFEFF")) {
            str = str.replace("\uFEFF", "");
        } else if (str.endsWith("\uFEFF")) {
            str = str.replace("\uFEFF", "");
        }
        return str;
    }
}
